using System;
using System.Collections.Generic;
using FireStarterModeller.BO;
using FireStarterModeller.Logic;
using Habanero.Faces.Base;
using Microsoft.Practices.Unity;

namespace FireStarterModeller.UI.Relationship
{
    public class CreateRelationshipWizardController : WizardController
    {
        private readonly IDMClass _dmClass;
        private readonly CreateRelationshipWizardStep1 _step1; //Select Related Class
        private readonly CreateRelationshipWizardStep2 _step2; //Step Only used if FK in Owner or Related
        //Class does not have matching Foreign key props. User can select Cardinality of Rel and whether to 
        // Create related props or not. 
        //Also called when r/ship is self referencing
        private readonly CreateRelationshipWizardStep3 _step3; //Confirm what has been done for the
        // relationship.
        private readonly CreateRelationshipWizardStep4 _step4; //Final Confirmation and any warnings.
        public DMRelationshipCreator RelationshipCreator { get; private set; }

        public CreateRelationshipWizardController(IUnityContainer container, IDMClass dmClass)
        {
            _dmClass = dmClass;
            if (container == null) throw new ArgumentNullException("container");
            if (dmClass == null) throw new ArgumentNullException("dmClass");
            container.RegisterInstance(dmClass);
            RelationshipCreator = container.Resolve<DMRelationshipCreator>();
            IControlFactory controlFactory = GlobalUIRegistry.ControlFactory;
            _step1 = new CreateRelationshipWizardStep1(RelationshipCreator, controlFactory);
            _step2 = new CreateRelationshipWizardStep2(RelationshipCreator, controlFactory);
            _step3 = new CreateRelationshipWizardStep3(RelationshipCreator, controlFactory);
            _step4 = new CreateRelationshipWizardStep4(RelationshipCreator, controlFactory);
            AddStep(_step1);
            AddStep(_step2);
            AddStep(_step3);
            AddStep(_step4);
        }

        public override void CancelWizard()
        {
            base.CancelWizard();
            this.RelationshipCreator.CancelAllEdits();
        }

        public override IWizardStep GetNextStep()
        {
            if (CurrentStep >= WizardSteps.Count - 1)
                throw new WizardStepException("Invalid Wizard Step: " + (CurrentStep + 1));

            if (GetCurrentStep() == _step1)
            {
                if (this.RelationshipCreator.CanFindForeignKey && !(_step1.RelatedClassComboBox.SelectedItem == _dmClass))
                {
                    //Skip step 2 and Setup Relationship
                    CurrentStep = WizardSteps.IndexOf(_step2);
                }
            }
            IWizardStep nextStep = base.GetNextStep();
            return nextStep;
        }

    }
}